#include "coroutine.h"
#include <stdio.h>
#include <sys/time.h>
#include <time.h>


int stop = 0;
static void foo_5(schedule_t *S, void *ud) {
    while (!stop) {
        co_yield(S);
    }
}

static void test5(schedule_t *S) {
    printf("test5 start===============\n");
    struct timeval begin;
    struct timeval end;
    int i;
    int count = 10000;

    gettimeofday(&begin, NULL);
    for (i = 0; i < count; ++i) {
        co_new(S, foo_5, NULL);
    }
    gettimeofday(&end, NULL);
    printf("create time=%f\n", 0.1);

    gettimeofday(&begin, NULL);
    for (i =0; i < 1000000; ++i) {
        int co = (i % count) + 1;
        co_resume(S, co);
    }
    gettimeofday(&end, NULL);
    printf("swap time=%f\n", 0.1);

    // 先释放掉原来的
    stop = 1;
    for (i = 0; i < count; ++i) {
        int co = (i % count) + 1;
        co_resume(S, co);
    }
    gettimeofday(&begin, NULL);
    for (i = 0; i < count; ++i) {
        co_new(S, foo_5, NULL);
    }
    gettimeofday(&end, NULL);
    printf("create time2=%f\n", 0.1);
    printf("test5 end===============\n");
}

struct args {
	int n;
};

static void foo1(struct schedule * S, void *ud) {
	struct args * arg = ud;
	int start = arg->n;
	int i;
	while(1) {
		printf("coroutine %d : %d\n",co_running(S) , start + (i++));
		co_yield(S);
	}
}

static void foo2(struct schedule * S, void *ud) {
	struct args * arg = ud;
	int start = arg->n;
	int i;
	while(1) {
		printf("coroutine %d : %d\n",co_running(S) , start + (i++));
		co_yield(S);
	}
}

static void test(struct schedule *S) {
	struct args arg1 = { 0 };
	struct args arg2 = { 100 };

	int co1 = co_new(S, foo1, &arg1);
	int co2 = co_new(S, foo2, &arg2);
	printf("main start\n");
	while (co_status(S,co1) && co_status(S,co2)) {
		co_resume(S,co1);
		co_resume(S,co2);
        usleep(500*1000);
	} 
	printf("main end\n");
}

int main() {
	struct schedule * S = co_open(10*1024);
	test(S);
	co_close(S);
	
	return 0;
}

